/*
* Copyright 2016 YONYOU Corporation Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project         marketing

* @Package         com.yonyou.marketing.message.push.provider.impl

* @Author          LuZhen

* @FileName        AbstractMessageProvideAdapter

* @Date            16/11/10

----------------------------------------------------------------------------------
*     Date          Who             Version         Comments
* 1. 16/11/10        LuZhen          1.0             Create Source
*
----------------------------------------------------------------------------------
*/
package com.yonyou.gmmc.service.wechatpush.provider.impl;

import com.yonyou.gmmc.service.wechatpush.common.HttpClientUtil;
import com.yonyou.gmmc.service.wechatpush.provider.*;
import com.yonyou.gmmc.service.wechatpush.resolver.PushMessage;
import com.yonyou.gmmc.service.wechatpush.spi.webchattools.*;

import java.util.List;

import org.apache.log4j.Logger;
import org.marketing.common.constants.MessagePushConstant;
import org.marketing.common.entity.wechatpushmessage.WeChatMessageProtocol;
import org.marketing.common.util.CommonUtils;
import org.marketing.common.util.SerializeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MessageProvideAdapterImpl implements MessageProvideAdapter {

    private final static Logger logger = Logger.getLogger(MessageProvideAdapterImpl.class);

    @Autowired
    private PushMessageHandleHistoryRepository repository;
//
//    @Autowired
//    private RestTemplate restTemplate;

    @Autowired
    private WxMpTemplateMsgService service;

    @Autowired
    private WebChatToolsConfig config;

    @Override
    public MessagePushResult push2Provider(ProviderMessage providerMessage) {
        if(providerMessage==null)
        {
            logger.error("ProviderMessage is null");
            return new MessagePushResult(false,"ProviderMessage is null");
        }
        MessagePushResult result;
        WeChatMessageProtocol origin = providerMessage.getOrigin().getOrigin();
        if(origin.getPushChannel().equals(MessagePushConstant.PUSH_CHANNEL.TEST)){
            result = new MessageDemoProvide().pushDemoMessage(providerMessage);
        }
        //web chat
        else if(origin.getPushChannel().equals(MessagePushConstant.PUSH_CHANNEL.WEBCHAT)) {
            result= pushTemplateMessage(providerMessage);
        }else{
            logger.error("ProviderMessage channel is error");
            result = new MessagePushResult(false,"ProviderMessage channel is error");
        }
        log2DataBase(providerMessage,result);
        return result;

    }

    /**
     * 记录日志
     * @param providerMessage   ProviderMessage
     * @param result    MessagePushResult
     */
    @Transactional
    private void log2DataBase(ProviderMessage providerMessage, MessagePushResult result) {
        logger.debug("@@result = "+result);
        List<String> receiverList = providerMessage.getOrigin().getOrigin().getReceiver().getDetailList();
        if(CommonUtils.isNullOrEmpty(receiverList)){
            logger.warn("rabbitMq message-receiverList is empty");
            return;
        }
        //记录消息
        for(String receiverId:receiverList){
            PushMessageHandleHistory history = new PushMessageHandleHistory(providerMessage,result,receiverId);
            repository.save(history);
        }
    }



    @Override
    public ProviderMessage trans2Provider(PushMessage pushMessage) {
        if(pushMessage.getOrigin().getPushChannel().equals(MessagePushConstant.PUSH_CHANNEL.TEST)){
            ProviderMessage message =  new ProviderDemoMessage();
            message.fillContent(pushMessage);
            return message;
        }
        if(pushMessage.getOrigin().getPushChannel().equals(MessagePushConstant.PUSH_CHANNEL.WEBCHAT)) {
            return transTemplate(pushMessage);
        }else{
            return null;
        }
    }

    public ProviderMessage transTemplate(PushMessage pushMessage) {
        if(pushMessage.getOrigin().getReceiver().getPlatform().equals(MessagePushConstant.PUSH_PLATFORM.WC_PUBLIC)){
            ProviderMessage message = new WebChatTemplateMessage();
            message.fillContent(pushMessage);
            return message;
        }else{
            return null;
        }
    }


    /**
     * 实际调用方法
     * @param   providerMessage      providerMessage
     * @param   accessToken          accessToken
     * @return  MessagePushResult
     */
    public MessagePushResult pushTemplateMessage(ProviderMessage providerMessage,String accessToken){
        if(providerMessage.getPlatForm().equals(MessagePushConstant.PUSH_PLATFORM.WC_PUBLIC)){
            WebChatTemplateMessage message = (WebChatTemplateMessage) providerMessage;
            logger.debug("WebChatTemplateMessage is "+message);

            //根据shortID动态获取templateId
            String templateShortId = message.getOrigin().getOrigin().getMessage().getContent();
//            WxMpAddTemplateResponse newTemplate = service.addTemplate(templateShortId,accessToken);
//            //动态新增模板
//            if(newTemplate==null||!newTemplate.isSucceed()){
//                logger.error("dynamic add new Template error");
//                return new MessagePushResult(false,"dynamic add new Template error");
//            }
            String authorizerAppid = providerMessage.getOrigin().getOrigin().getSender().getClientAppId();
            

            
            if(CommonUtils.isNullOrEmpty(templateShortId) || CommonUtils.isNullOrEmpty(authorizerAppid)){
                logger.error("send params is empty,templateShortId or authorizerAppid");
                return new MessagePushResult(false,"send params is empty,templateShortId or authorizerAppid");

            }
            
            //获取模板ID
            String templateIdUrl = config.getDealerTemplateIdUrl().replace("$AUTHORIZERAPPID",authorizerAppid)
                    .replace("$TEMPLATENUM", templateShortId);
            String templateId = HttpClientUtil.sendGetRequest(templateIdUrl);

            logger.info("pushTemplateMessage-templateIdUrl="+templateIdUrl);
//            logger.info("pushTemplateMessage-templateId="+templateId);
            message.getMessage().setTemplateId(templateId);
            
            logger.info("pushTemplateMessage-message.getMessage()="+SerializeUtils.serialize(message.getMessage()));
            //message.getMessage().setTemplateId("N2FlDzqqerxvlLHRM7cBZGj9A3UCkazk8baVYWKy1J4");
            
            //发送模板
            WxMpSendTemplateMessageResponse result = service.sendTemplateMsg(message.getMessage(),accessToken);
            if(result==null||!result.isSucceed()){
                if(result!=null){
                    logger.error("send Template message error "+result);
                }

                return new MessagePushResult(false,"send Template message error");
            }
            logger.info("WebChatTemplateMessage result is "+result.getMessageId());
            return new MessagePushResult(true,result.getMessageId());

        }
        logger.error("error platform ");
        return new MessagePushResult(false,"error platform ");
    }


    private MessagePushResult pushTemplateMessage(ProviderMessage providerMessage) {
        //
        if(providerMessage.getPlatForm().equals(MessagePushConstant.PUSH_PLATFORM.WC_CUSTOMER)){
            return new MessagePushResult(false,"暂时不支持客服消息");
        }
        //使用
//        String str = "5zsRcZhP4CLSODDX_ipsfDCVcADrQf3pozextXXXmylyEz0_45goKgaYeHjkgZUZc3xGjld47gANXM9_Fh1gCEUrdg-nc9MT2peTWnJj4uk8N67EfWSoMxli7I7MeEAJJNIdAEDOSN";
        String accessToken;
        try {
            String tokenRequestUrl = config.getWebChatTokenUrl().replace("$authorizerAppid",providerMessage.getOrigin().getOrigin().getSender().getClientAppId());
            logger.info("pushTemplateMessage-tokenRequestUrl="+tokenRequestUrl);
            accessToken = HttpClientUtil.sendGetRequest(tokenRequestUrl);

        } catch (Exception e) {
            logger.error(e);
            return new MessagePushResult(true,e.getMessage());
        }
        if(CommonUtils.isNullOrEmpty(accessToken)){
            logger.error("access token is null");
            return new MessagePushResult(true,"access token is null");
        }
        return pushTemplateMessage(providerMessage,accessToken);
    }

}
